
package org.masterinftel.scrumpmt.activities;

import java.util.List;

import org.masterinftel.scrumpmt.Constants;
import org.masterinftel.scrumpmt.R;
import org.masterinftel.scrumpmt.ScrumApplication;
import org.masterinftel.scrumpmt.json.model.AddSprintJSON;
import org.masterinftel.scrumpmt.json.model.ColaboradorJSON;
import org.masterinftel.scrumpmt.json.model.SprintJSON;
import org.masterinftel.scrumpmt.json.model.TareaJSON;
import org.masterinftel.scrumpmt.protocol.Protocol;
import org.masterinftel.scrumpmt.util.UtilNetwork;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

import com.google.gson.Gson;

public class AddToSprintActivity extends Activity {
    private Spinner cmbSprints;
    private Spinner cmbColaboradores;
    private ProgressDialog progressDialog;
    private Context ctx;
    private ScrumApplication application;
    private List<ColaboradorJSON> colList;
    private List<SprintJSON> sprintList;
    private String URLFrontController;
    private long tarea;
    private int selectedTarea;
    private String sprint;
    private String colaborador;
    private List<TareaJSON> datos;

    // Manejador asincrono de las peticiones de los productos
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            progressDialog.dismiss();
            switch (msg.what) {
                case 0:
                    Intent intent = new Intent(ctx, BacklogActivity.class);
                    datos.get(selectedTarea).setColabName(colaborador);
                    datos.get(selectedTarea).setSprint(sprint);
                    startActivity(intent);
                    break;
            }
        }

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addtasktosprint);
        setTitle("ScrumPMT - Añadir a sprint");
        tarea = getIntent().getLongExtra("position", 99999999);
        selectedTarea = getIntent().getIntExtra("selected", 99999999);
        Log.d(Constants.LOGTAG, "Tar: " + tarea);

        // creamos variables utiles para la aplicacion
        ctx = this;
        application = (ScrumApplication) getApplication();
        datos = getTask();

        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(ctx);
        URLFrontController = prefs.getString(Constants.KEY_URL_PREFERENCE, "");

        Button btnGuardar = (Button) findViewById(R.id.BAddTaskSprint);

        colList = application.getColabAll();
        String[] cols =
                new String[colList.size()];
        int i = 0;
        for (ColaboradorJSON c : colList) {

            cols[i] = c.getNombre();
            i++;
        }
        sprintList = application.getSprints();
        String[] sprints =
                new String[sprintList.size()];
        i = 0;
        for (SprintJSON s : sprintList) {

            sprints[i] = s.getDes();
            i++;
        }

        ArrayAdapter<String> adaptadorSprint =
                new ArrayAdapter<String>(this,
                        android.R.layout.simple_spinner_item, sprints);
        ArrayAdapter<String> adaptadorCols =
                new ArrayAdapter<String>(this,
                        android.R.layout.simple_spinner_item, cols);

        adaptadorSprint.setDropDownViewResource(
                android.R.layout.simple_spinner_dropdown_item);
        cmbSprints = (Spinner) findViewById(R.id.SSprintAddTS);
        cmbSprints.setAdapter(adaptadorSprint);

        adaptadorCols.setDropDownViewResource(
                android.R.layout.simple_spinner_dropdown_item);
        cmbColaboradores = (Spinner) findViewById(R.id.SColAddTs);
        cmbColaboradores.setAdapter(adaptadorCols);

        btnGuardar.setOnClickListener(mAddTaskToSprintListener);

    }

    // Manejador del crear
    OnClickListener mAddTaskToSprintListener = new OnClickListener() {
        @Override
        public void onClick(final View v) {
            progressDialog = ProgressDialog.show(ctx, "Conectando...",
                    " Asigando tarea a sprint", true, false);
            new Thread() {
                public void run() {
                    String urlRest = URLFrontController + ";jsessionid="
                            + application.getSessionID() + "?action="
                            + Protocol.ADD_TAREA_SPRINT + "&value=" + tarea;

                    sprint = (String) cmbSprints.getSelectedItem();
                    colaborador = (String) cmbColaboradores.getSelectedItem();
                    AddSprintJSON ads = new AddSprintJSON(sprint, colaborador);

                    Log.i(Constants.LOGTAG, "Le envio al server: " + new Gson().toJson(ads));
                    UtilNetwork.insertJSON(urlRest, ads);
                    handler.sendEmptyMessage(0);
                }
            }.start();
        }
    };

    private List<TareaJSON> getTask() {

        return application.getTareas();
    }
}
